const express = require('express');
const path = require('path');
const request = require('request');
const bodyParser = require('body-parser');
const app = express();
const config = require("./config").config;
const Util = require("./src/lib/commonJs");
const { certification , qr } = require('./service/certification/certification');
const email = require("emailjs");
const axios = require("axios");

const pattern = config.type;
// const pattern = "prod";

const logger = {
    entry:(msg)=>{
	console.log(`GET >>> ${Util.timeFormat(new Date(),"yyyy-MM-dd hh:mm:ss")} >>> ${msg}`);
    }
};

app.use(express.static(path.join(__dirname, 'public')));

/*app.get('/',function(req,res){
    res.sendFile(path.join(__dirname,'public/index.html'))
});*/

let getTxByHash = (hash)=>{
    return new Promise((suc,err)=>{
	axios({
	    method: 'get',
	    url:`${config.host}/gettransaction?hashData=${encodeURIComponent(hash)}`,
	}).then((data)=>{
	    console.log(`参数已返回:::${JSON.stringify(data.data)}`);
	    if(typeof data.data !== "undefined" && data.data !== null && data.data.State===200){
		let baseTool = new Util.Base64();
		let certInfo = JSON.parse(baseTool.decode(data.data.Data.smartContractArgs[2]));
		suc({
		    code:200,
		    data:certInfo,
		});
	    }else{
		suc({
		    code:400,
		    data:"",
		});
		console.log(`err:::${data.data.Message}:::${JSON.stringify(data.data.Data)}`)
	    }
	});
    })
};

app.use(bodyParser.urlencoded({ extended: false }));//
// app.use(bodyParser.json());

app.get('/certs/getCert',(req, res)=>{
    logger.entry("/certs/getCert");
    if(pattern === "dev"){
	certification(
	    "201701000",
	    "马小峰",
	    "2017年8月5日",
	    "2017年8月27日",
	    "第一期",
	    "9VRM/eoMVFhgOui1kKFYWkxnlPXjw1mVdfxeZs8kDj0=",
	    "2017年8月27日",
	    "18516177536",
	    (reData)=>{
		res.end(reData);
	    }
	);
	return;
    }
    let txHex = req.query.txHex;
    if(Util.isEmpty(txHex)){
	res.json({
	    code:400,
	    data:"请求失败,参数为空。"
	});
    }else{
	console.log(`发送参数:::${txHex}`);
	getTxByHash(txHex).then((data)=>{
	    if(data.code === 200){
		let certInfo = data.data;
		certification(
		    certInfo.certificateNum,
		    certInfo.name,
		    certInfo.trainTime,
		    certInfo.authenTime,
		    certInfo.term,
		    txHex,
		    certInfo.authenTime,
		    certInfo.phone,
		    (reData)=>{
			res.end(reData);
		    }
		);
	    }else{
		res.json({
		    code:400,
		    data:"请求失败。"
		});
	    }
	});
    }

    /*axios({
	method: 'get',
	url:`${config.host}/gettransaction?hashData=${encodeURIComponent(txHex)}`,
    }).then((data)=>{
	console.log(`参数已返回:::${JSON.stringify(data.data)}`);
	if(typeof data.data !== "undefined" && data.data !== null && data.data.State===200){
	    let baseTool = new Util.Base64();
	    let certInfo = JSON.parse(baseTool.decode(data.data.Data.smartContractArgs[2]));
	    certification(
		certInfo.certificateNum,
		certInfo.name,
		certInfo.trainTime,
		certInfo.authenTime,
		certInfo.term,
		txHex,
		certInfo.authenTime,
		certInfo.phone,
		(reData)=>{
		    res.end(reData);
		}
	    );
	}else{
	    res.json({
		code:400,
		data:"请求失败。"
	    });
	    console.log(`err:::${data.data.Message}:::${JSON.stringify(data.data.Data)}`)
	}
    });*/
});
app.get('/certs/getCertInfo',(req, res)=>{
    logger.entry("/certs/getCertInfo");
    if(pattern === "dev"){
	res.json({
	    code:200,
	    data:{
		certificateNum:"201701000",
		name: "马小峰",
		trainTime:"2017年8月5日",
		authenTime:"2017年8月27日",
		term:"第一期",
		phone: "18516177536",
		mailbox: "无信息",
		institution: "苏州同济金融科技研究院",
		position: "院长"
	    }
	});
	return;
    }

    let txHex = req.query.hashData;

    if(Util.isEmpty(txHex)){
	res.json({
	    code:400,
	    data:"请求失败,参数为空。"
	});
    }else{
	console.log(`发送参数:::${txHex}`);
	getTxByHash(txHex).then((data)=>{
	    res.json(data);
	});
    }


    /*let reHex = encodeURIComponent(txHex);

    request.get({
	url: `${config.host}/gettransaction?hashData=${reHex}`,
    }, function(error, response, body) {
	error?console.log(`error::::::${error}`):"";
	console.log(`参数已返回:::${body}`);
	let data = JSON.parse(body);
        if(data.State === 200){
	    let baseTool = new Util.Base64();
	    let $$data = baseTool.decode(data.Data.smartContract).split(" ")[2];
	    let $$$data = baseTool.decode($$data);
	    res.json({
		code:200,
		data:JSON.parse($$$data)
	    });
	}else{
	    res.json({
		code:400,
		data:"请求失败。"
	    });
	    console.log(`err:::${data.Message}:::${JSON.stringify(data.Data)}`)
	}
    })*/
});
app.get('/certs/getqr',(req, res)=>{
    logger.entry("/certs/getqr");
    if(pattern === "dev"){
	const qr_PNG = qr.imageSync("http://cert.tj-fintech.com?fromQr=asdasd", {
	    type: 'png',
	    size:3,
	    margin:1
	});
	res.end(qr_PNG);
	return;
    }
    let txHex = req.query.hashData;
    if(!Util.isEmpty(txHex)){
	// txHex = txHex.replace(/2B%/g,"+");
    }else{
	res.json({
	    code:400,
	    data:"请求失败,参数为空。"
	});
	return false;
    }
    const qr_PNG = qr.imageSync("http://cert.tj-fintech.com?fromQr="+txHex, {
	type: 'png',
	size:3,
	margin:1
    });
    res.end(qr_PNG);
});


app.post('/chainvalley/join',(req, res)=>{
    let server 	= email.server.connect({
	user:       "yulinzhen@tj-fintech.com",
	password:   "Yu65632625",
	host:       "smtp.exmail.qq.com",
	port:       465,
	ssl:        true
    });
    let [firstName, lastName, businessEmail, phone, company, jobTitle, address, detail,] = [
	req.body.firstName,
	req.body.lastName,
	req.body.businessEmail,
	req.body.phone,
	req.body.company,
	req.body.jobTitle,
	req.body.address,
	req.body.detail,
    ];
    let message	= {
	text:"链谷 - 加入请求",
	from:"yulinzhen@tj-fintech.com",
	to:"yulinzhen@tj-fintech.com,yewei@tj-fintech.com,yaomengdi@tj-fintech.com",
	subject:"链谷 - 加入请求",
	attachment:[{
	    data:
            "<html>" +
            "<i>本条内容为 链谷 后台自动发送</i><br/>" +
            `First Name: ${ firstName }<br/>` +
            `Last Name: ${ lastName }<br/>` +
            `Business Email: ${ businessEmail }<br/>` +
            `Phone: ${ phone }<br/>` +
            `Company: ${ company }<br/>` +
            `Job Title: ${ jobTitle }<br/>` +
            `Address: ${ address }<br/>` +
            `Detail: ${ detail }<br/>` +
            "</html>",
	    alternative:true
	}]
    };
    if(Util.isEmpty(firstName,lastName,businessEmail,phone)){
	res.json({
	    code:400,
	    data:"发送失败，请将信息填写完整。"
	});
    }else{
	server.send(message, function (err, message) {
	    res.json({
		code:200,
		data:"已发送"
	    });
	});
    }
});

app.listen(config.port, function() {
    console.log('=================》》Production Express server running at localhost:' + config.port)
});